<template>
  <page-container title="征文比赛">
    <!-- 头部右侧仅保留“我的参赛记录”按钮 -->
    <template #extra>
      <el-button type="default" icon="User" size="small">
        我的参赛记录
      </el-button>
    </template>
    <div class="essay-competition">
      <!-- 1. 比赛统计卡片（保持原有统计项） -->
      <el-row :gutter="20" class="summary-cards" style="margin-bottom: 24px;">
        <el-col :span="6" :xs="12" :sm="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.onGoingCount || 0 }}</div>
              <div class="stat-label">进行中比赛</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" :xs="12" :sm="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.pendingReviewCount || 0 }}</div>
              <div class="stat-label">待评审作品</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" :xs="12" :sm="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.myParticipationCount || 0 }}</div>
              <div class="stat-label">我的参赛数</div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6" :xs="12" :sm="8">
          <el-card shadow="hover" class="stat-card">
            <div class="stat-item">
              <div class="stat-value">{{ summary.awardedCount || 0 }}</div>
              <div class="stat-label">已获奖数</div>
            </div>
          </el-card>
        </el-col>
      </el-row>
      <!-- 2. 全部比赛列表（合并进行中/已结束） -->
      <el-card shadow="hover" class="competition-list-card">
        <el-row :gutter="24" v-loading="loading" v-if="competitions.length > 0">
          <el-col :span="12" :xs="24" :md="8" 
            v-for="(comp, index) in competitions" 
            :key="`comp-${comp.id}`"
          >
            <div class="competition-card" :class="{ 'ended-card': comp.status === '已结束' }">
              <div class="comp-cover">
                <!-- 已结束比赛添加遮罩 -->
                <div v-if="comp.status === '已结束'" class="ended-mask"></div>
                <img :src="comp.coverUrl" alt="比赛封面" class="cover-img">
                <!-- 根据状态显示不同类型的标签 -->
                <el-tag 
                  class="comp-status-tag" 
                  :type="getStatusTagType(comp.status)"
                >
                  {{ comp.status }}
                </el-tag>
              </div>
              <div class="comp-info">
                <h3 class="comp-name">{{ comp.name }}</h3>
                <div class="comp-meta">
                  <span class="meta-item">
                    <i class="el-icon-building" style="margin-right: 4px;"></i>
                    {{ comp.organizer }}
                  </span>
                  <span class="meta-item">
                    <i class="el-icon-calendar" style="margin-right: 4px;"></i>
                    {{ comp.dateRange }}
                  </span>
                </div>
                <div class="comp-reward">
                  <i class="el-icon-gift" style="margin-right: 4px; color: #f56c6c;"></i>
                  <span class="reward-text">奖金：{{ comp.reward }}</span>
                </div>
                <div class="comp-requirement">
                  <span class="requirement-label">参赛要求：</span>
                  <span class="requirement-content">{{ comp.requirement }}</span>
                </div>
              </div>
              <div class="comp-actions">
                <el-button type="text" size="small" @click="handleViewDetail(comp)">
                  查看详情
                </el-button>
                <!-- 根据状态显示“立即参赛”或“查看结果”按钮 -->
                <el-button 
                  :type="comp.status === '进行中' ? 'primary' : 'default'" 
                  size="small" 
                  @click="handleAction(comp)" 
                  style="margin-left: auto;"
                >
                  {{ comp.status === '进行中' ? '立即参赛' : '查看结果' }}
                </el-button>
              </div>
            </div>
          </el-col>
        </el-row>
        <!-- 空状态 -->
        <el-empty 
          v-else
          description="暂无征文比赛记录"
          class="empty-tip"
        />
        <!-- 分页 -->
        <div class="pagination" style="margin-top: 20px; text-align: right;">
          <el-pagination
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="currentPage"
            :page-sizes="[6, 12, 24]"
            :page-size="pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCompetitions"
          />
        </div>
      </el-card>
    </div>
  </page-container>
</template>

<script setup>
import { ref, watch, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import PageContainer from '@/components/PageContainer.vue';
import { getCompetitionList } from '@/api/other'; 

// 分页与加载状态
const currentPage = ref(1);
const pageSize = ref(6);
const loading = ref(false);

// 统计数据（仅保留非状态关联的统计项，“进行中比赛”通过计算属性实时统计）
const summary = ref({
  pendingReviewCount: 12,
  myParticipationCount: 2,
  awardedCount: 1
});

// 接口数据存储（合并为一个数组）
const competitions = ref([]);
const totalCompetitions = ref(0);

// 计算属性：实时统计“进行中比赛”数量
const onGoingCount = computed(() => {
  return competitions.value.filter(comp => comp.status === '进行中').length;
});
summary.value.onGoingCount = onGoingCount.value; // 初始化统计值

// 格式化接口数据为组件所需格式
const formatCompetitionData = (list) => {
  console.log('【征文列表】格式化前原始数据：', JSON.parse(JSON.stringify(list)));
  
  const formattedList = list.map(item => ({
    id: item.id,
    name: item.title,
    coverUrl: item.cover || 'https://picsum.photos/id/100/400/200',
    organizer: item.creatorName || '未知主办方',
    status: item.status, // 直接使用接口返回的状态（进行中/已结束/未开始）
    dateRange: `${item.startDate} 至 ${item.endDate}`,
    reward: item.awards || '无',
    requirement: item.rules || '无特殊要求',
    detailUrl: `#/competition/detail/${item.id}`,
  }));

  console.log('【征文列表】格式化后数据：', JSON.parse(JSON.stringify(formattedList)));
  return formattedList;
};

// 根据比赛状态返回标签类型
const getStatusTagType = (status) => {
  switch (status) {
    case '进行中': return 'primary';
    case '已结束': return 'info';
    case '未开始': return 'warning';
    default: return 'default';
  }
};

// 接口请求：获取**所有状态**的征文列表（去掉status筛选）
const fetchCompetitions = async () => {
  loading.value = true;
  const requestParams = {
    page: currentPage.value,
    limit: pageSize.value,
    // 去掉status筛选，获取所有状态的比赛
  };

  console.log('【征文列表】发起接口请求：', {
    apiUrl: '/article/getCompetitionList',
    requestParams,
    requestTime: new Date().toLocaleString()
  });

  try {
    const res = await getCompetitionList(requestParams);
    console.log('【征文列表】接口原始响应：', res);

    const { code, msg, data } = res.data; 

    if (code === '0000') {
      const formattedList = formatCompetitionData(data.list);
      const { total } = data.pagination;

      competitions.value = formattedList;
      totalCompetitions.value = total;
      summary.value.onGoingCount = onGoingCount.value; // 同步统计值
    } else {
      console.error('【征文列表】接口业务错误：', {
        errorCode: code,
        errorMsg: msg,
        requestParams
      });
      ElMessage.error(`获取征文比赛列表失败：${msg}`);
    }
  } catch (err) {
    console.error('【征文列表】接口请求异常：', {
      errorMsg: err.message,
      errorStack: err.stack,
      requestParams
    });
    ElMessage.error('服务异常，无法获取比赛列表');
  } finally {
    loading.value = false;
    console.log('【征文列表】请求结束：', {
      loadingStatus: loading.value,
      endTime: new Date().toLocaleString()
    });
  }
};

// 生命周期：挂载时初始化数据
onMounted(() => {
  console.log('【征文比赛组件】挂载完成，触发首次接口请求');
  fetchCompetitions();
});

// 监听分页变化，重新请求数据
watch([currentPage, pageSize], ([newPage, newSize], [oldPage, oldSize]) => {
  console.log('【征文比赛组件】分页状态变化：', {
    pageChange: { old: oldPage, new: newPage },
    sizeChange: { old: oldSize, new: newSize }
  });
  fetchCompetitions();
}, { deep: true });

// 操作函数：根据比赛状态执行不同逻辑
const handleAction = (comp) => {
  if (comp.status === '进行中') {
    ElMessage.success(`已进入《${comp.name}》参赛页面`);
  } else {
    ElMessage.info(`查看《${comp.name}》比赛结果`);
  }
};

// 分页操作函数
const handleSizeChange = (val) => {
  console.log('【征文比赛组件】用户修改页大小：', { oldSize: pageSize.value, newSize: val });
  pageSize.value = val;
};

const handleCurrentChange = (val) => {
  console.log('【征文比赛组件】用户切换页码：', { oldPage: currentPage.value, newPage: val });
  currentPage.value = val;
};

// 查看详情操作
const handleViewDetail = (comp) => {
  console.log('【征文比赛组件】用户点击查看详情：', { competitionId: comp.id, competitionName: comp.name });
  ElMessage.info(`查看《${comp.name}》详情`);
};
</script>

<style lang="scss" scoped>
/* 原有样式不变，保持UI一致性 */
.essay-competition {
  .summary-cards {
    .stat-card {
      .stat-item {
        text-align: center;
        padding: 20px 0;
        .stat-value {
          font-size: 24px;
          font-weight: bold;
          color: #409eff;
          margin-bottom: 8px;
        }
        .stat-label {
          font-size: 14px;
          color: #909399;
        }
      }
    }
  }
  .competition-list-card {
    .empty-tip {
      padding: 60px 0;
    }
  }
  .competition-card {
    border: 1px solid #e4e7ed;
    border-radius: 8px;
    overflow: hidden;
    background-color: #fff;
    transition: all 0.3s;
    display: flex;
    flex-direction: column;
    height: 100%;
    &:hover {
      border-color: #409eff;
      box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.08);
    }
    &.ended-card {
      .comp-cover {
        .ended-mask {
          position: absolute;
          top: 0;
          left: 0;
          width: 100%;
          height: 100%;
          background-color: rgba(0, 0, 0, 0.1);
          z-index: 1;
        }
      }
    }
    .comp-cover {
      position: relative;
      height: 140px;
      .cover-img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      .comp-status-tag {
        position: absolute;
        top: 8px;
        right: 8px;
        z-index: 2;
      }
    }
    .comp-info {
      padding: 12px;
      flex: 1;
      display: flex;
      flex-direction: column;
      .comp-name {
        font-size: 16px;
        font-weight: 500;
        color: #303133;
        margin-bottom: 8px;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
      .comp-meta {
        display: flex;
        flex-wrap: wrap;
        font-size: 12px;
        color: #909399;
        margin-bottom: 8px;
        .meta-item {
          margin-right: 12px;
          margin-bottom: 4px;
        }
      }
      .comp-reward,
      .comp-requirement {
        font-size: 12px;
        margin-bottom: 6px;
        line-height: 1.5;
        .reward-text,
        .requirement-content {
          color: #606266;
        }
        .requirement-label {
          color: #909399;
          margin-right: 4px;
        }
        .requirement-content {
          display: -webkit-box;
          -webkit-line-clamp: 2;
          -webkit-box-orient: vertical;
          overflow: hidden;
        }
      }
    }
    .comp-actions {
      display: flex;
      align-items: center;
      padding: 8px 12px;
      border-top: 1px solid #f2f2f2;
      button {
        font-size: 12px;
      }
    }
  }
}
@media (max-width: 768px) {
  .essay-competition {
    .competition-list-card {
      .el-row {
        .el-col {
          &:nth-child(n) {
            width: 100%;
            margin-bottom: 16px;
          }
        }
      }
    }
  }
}
</style>